/**
 * 
 */
package com.totobox.apps.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;

import android.widget.ProgressBar;
import android.widget.TextView;

import com.totobox.apps.Const;

/**
 * @author ytslove
 * 
 */
public class DownloadFile extends Thread{

	String t_filename;
	String t_file_url;
	int total_curRate = 0;
	
	String downDir = Const.homeDir + Const.movieDir;
	
	private int DOWNLOAD_DONE = 0;
	private int DEFAULT_TIMEOUT = 5000;
	
	private ProgressBar progress;
	private TextView txtView;
	
	public DownloadFile(String url){
    	this.t_file_url = url;
    	//this.execute();
    }
    
	
    public void down(String url , ProgressBar progress , TextView txtView){
    	this.t_file_url = url;
    	this.progress = progress;
    	this.txtView = txtView;
    	this.execute();
    }
    
    
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try{
			
			while(true){
				this.execute();
			}
			
		} catch(Exception e){}
	}


	/*
	 * 실제 다운
	 */
	public void execute() {
		
		int count;
		
		URL url = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		byte data[] = new byte[1024];
		
		try {
			
			t_filename = getFileName(t_file_url);
			
			url = new URL(t_file_url);
			URLConnection conn = url.openConnection();
			conn.connect();
			
			int lenghtOfFile = conn.getContentLength(); // downlod the file
			
			bis = new BufferedInputStream(url.openStream());
			bos = new BufferedOutputStream(new FileOutputStream(downDir + t_filename));

			long total = 0;
			while ((count = bis.read(data)) != -1 ) {
				total += count;
				publishProgress((int) (total * 100 / lenghtOfFile));
				bos.write(data, 0, count);
				//if(isStop) synchronized (this) {wait();}
				//if(isCancelled()) break;
			}
			
			bos.flush();
				
		} catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{ if( bos != null ) bos.close(); }catch(Exception ex){}
            try{ if( bis != null ) bis.close(); }catch(Exception ex){}
        }
	}
	
	public void publishProgress(int rate){
		this.total_curRate = rate;
		progress.setProgress(rate);
		txtView.setText(rate + "%");
	}
	
	public int curRate(){
		return this.total_curRate;
	}
	
	/**
	 * 파일명 생성
	 * @param wholePath
	 * @return
	 */
	public String getFileName(String wholePath)
    {
        String name=null;
        int start,end;
        start=wholePath.lastIndexOf('/');
        end=wholePath.length();     //lastIndexOf('.');
        name=wholePath.substring((start+1),end);
        return name;
    }
	
/*
	public boolean down(String urlpath) {
		int count;
		BufferedInputStream input = null;
		BufferedOutputStream output = null;
		try {
			
			URL url = new URL(t_file_url);
			
			URLConnection conexion = url.openConnection();
			
			int lenghtOfFile = conexion.getContentLength(); // downlod the file
			
			input = new BufferedInputStream(url.openStream());
			
			output = new BufferedOutputStream(new FileOutputStream(""));

			byte data[] = new byte[1024];
			long total = 0;
			while ((count = input.read(data)) != -1) {
				total += count; // publishing the progress....
				//publishProgress((int) (total * 100 / lenghtOfFile));
				output.write(data, 0, count);
			}
			output.flush();
			output.close();
			input.close();
		} catch (Exception e) {
		}
		return true;
	}
	*/
	
	public boolean execute(String fileUri , String mUrl ,  long fileSize) {
		
        long remains = 0, lenghtOfFile = 0;
         
        BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		byte data[] = new byte[1024];
		
        try{
        	
        	 File file = new File(fileUri);
             if (file.exists() == false) {
                 file.createNewFile();
             }
        	
	        RandomAccessFile output = new RandomAccessFile(file.getAbsolutePath(), "rw");
	        fileSize = output.length(); 
	        output.seek(fileSize); 
	         
	        URL url = new URL(mUrl); 
	        URLConnection conn = url.openConnection(); 
	        conn.setRequestProperty("Range", "bytes=" + String.valueOf(fileSize) + '-'); //이어받기부분
	        conn.connect();
	        
	        conn.setConnectTimeout(DEFAULT_TIMEOUT); 
	        conn.setReadTimeout(DEFAULT_TIMEOUT); 
	        remains = conn.getContentLength(); 
	        lenghtOfFile = remains + fileSize; 
	         
	        if ((remains <= DOWNLOAD_DONE) || (remains == fileSize)) { 
	            return true; 
	        } 
	        InputStream input = conn.getInputStream(); 
	         
	        bis = new BufferedInputStream(url.openStream());
			bos = new BufferedOutputStream(new FileOutputStream(downDir + t_filename));
			
	        int count = 0; 
	         
	        if (fileSize < lenghtOfFile) { 
	            while((count = input.read(data)) != -1) { 
	                output.write(data, 0, count); 
	            } 
	        } 
	        output.close(); 
	        input.close();
	        
        } catch (Exception e) {
		}
        
        return true;

	}
}
